/**
 * 中间件统一导出
 */

// 错误处理中间件
export {
  errorHandler,
  AppError,
  ErrorCodes,
  createError
} from './errorHandler';

// CORS中间件
export {
  cors,
  createDevCors,
  createProdCors,
  type CorsOptions
} from './cors';

// 日志中间件
export {
  logger,
  createDevLogger,
  createProdLogger,
  createDetailedLogger,
  LogLevel,
  type LoggerOptions
} from './logger';

// 中间件组合函数
import Koa from 'koa';
import { errorHandler } from './errorHandler';
import { cors, createDevCors, createProdCors } from './cors';
import { logger, createDevLogger, createProdLogger } from './logger';
import { config } from '../config';

/**
 * 应用所有基础中间件
 */
export const applyMiddleware = (app: Koa) => {
  // 1. 错误处理中间件（必须在最前面）
  app.use(errorHandler());
  
  // 2. 日志中间件
  if (config.nodeEnv === 'development') {
    app.use(createDevLogger());
  } else {
    app.use(createProdLogger());
  }
  
  // 3. CORS中间件
  if (config.nodeEnv === 'development') {
    app.use(createDevCors());
  } else {
    // 生产环境需要配置具体的允许域名
    const allowedOrigins = config.cors.origin.split(',').map(origin => origin.trim());
    app.use(createProdCors(allowedOrigins));
  }
};

/**
 * 应用开发环境中间件
 */
export const applyDevMiddleware = (app: Koa) => {
  app.use(errorHandler());
  app.use(createDevLogger());
  app.use(createDevCors());
};

/**
 * 应用生产环境中间件
 */
export const applyProdMiddleware = (app: Koa, allowedOrigins: string[]) => {
  app.use(errorHandler());
  app.use(createProdLogger());
  app.use(createProdCors(allowedOrigins));
};